package com.cloud.nio;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannel01 {

    public static void main(String[] args) {
        try {
            // 创建文件输入流
            File file = new File("d:\\file01.txt");
            FileInputStream fileInputStream = new FileInputStream(file);

            // 通过fileInputStream获取对应的filechannel -> FileChannelImpl
            FileChannel channel = fileInputStream.getChannel();

            // 创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate((int) file.length());

            // 将通道的数据读入到buffer中
            channel.read(buffer);

            // 将buffer的字节数据转成字符串
            System.out.println(new String(buffer.array()));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
